#!/usr/bin/perl 
#===============================================================================
#
#         FILE:  DB.pm
#
#        USAGE:  use DB;
#
#  DESCRIPTION:  Some functions for work with db.
# 
# REQUIREMENTS:  DBI.
#         BUGS:  ---
#        NOTES:  ---
#       AUTHOR:  Pavel Odintsov (nrg), <pavel.odintsov@gmail.com>
#      COMPANY:  
#      VERSION:  1.0
#      CREATED:  Mon Dev 10 23:53:08 SAMT 2007
#     REVISION:  ---
#===============================================================================

package DB;

use strict;
use warnings;
use Exporter 'import';
use DBI;

our @EXPORT = qw(db_connect db_disconnect vquery query ); 
our $VERSION = '1.0';

our %DB_CONFIG = (); # hash for db settings 
my $data_base_handle = ''; # variable for database handle
my $last_error = 'no error';


# connect to db, save db handle in private module variable $data_base_handle
sub db_connect {
    my $db_connect_string = "DBI:mysql:database=$DB_CONFIG{'db_name'};" .
                            "host=$DB_CONFIG{'db_host'};" . 
                            "port=$DB_CONFIG{'db_port'}"; # db connection string
    $data_base_handle = DBI->connect($db_connect_string, $DB_CONFIG{'db_user'}, $DB_CONFIG{'db_passwd'}, { PrintError => 1, 'RaiseError' => 1 })
}


# disconnect from db
sub db_disconnect {
    if ($data_base_handle) {
        return ($data_base_handle->disconnect) ? 1 : 0;
    }
    return 0;
}


# execute query to db with data (preferably for SELECT)
sub query {
    if ($data_base_handle) {
        unless ($data_base_handle && $data_base_handle->FETCH('Active') && eval { $data_base_handle->ping }) { # check db connect
            db_connect() or return;
        }
        map {
            $_->execute(@_); # execute query
            @{$_->fetchall_arrayref({})}; 
        } $data_base_handle->prepare(shift)
    } else {
        return;
    }
} 


# execute query to db without data (proferably for INSERT, DELETE, UPDATE)
sub vquery {
    if ($data_base_handle) {
        unless ($data_base_handle && $data_base_handle->FETCH('Active') && eval { $data_base_handle->ping }) { # check db connect
            db_connect() or return;
        }
        my $sql_request = shift;
        $data_base_handle->do($sql_request, undef, @_) if $data_base_handle; # standard DBI do request 
    } else {
        return;
    }
}


#vquery("INSERT INTO domains_info (domain,request_date,whois_info) VALUES(?,NOW(),?)", $domain, $domain_informaion);


1;
